﻿using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;

namespace QW.Found.JwtAuthorize
{
    /// <summary>
    /// 权限处理程序
    /// </summary>
    public class PermissionHandler : AuthorizationHandler<JwtAuthorizationRequirement>
    {
        private readonly IAuthenticationSchemeProvider _schemes;
        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="schemes"></param>
        public PermissionHandler(IAuthenticationSchemeProvider schemes)
        {
            _schemes = schemes;
        }
        /// <summary>
        /// 处理过程
        /// </summary>
        /// <param name="context">authorization handler context</param>
        /// <param name="requirement">jwt authorization requirement</param>
        /// <returns></returns>
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, JwtAuthorizationRequirement requirement)
        {
            /* 老代码玩法
            var httpContext = context.Resource.GetType().GetProperty("HttpContext").GetValue(context.Resource) as Microsoft.AspNetCore.Http.HttpContext;
            var handlers = httpContext.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
            foreach (var scheme in _schemes.GetRequestHandlerSchemesAsync().Result)
            {
                var handler = handlers.GetHandlerAsync(httpContext, scheme.Name) as IAuthenticationRequestHandler;
                if (handler != null && handler.HandleRequestAsync().Result)
                {
                    httpContext.Response.Headers.Add("error", "request cancel");
                    context.Fail();
                    return Task.CompletedTask;
                }
            }
            var defaultAuthenticate = _schemes.GetDefaultAuthenticateSchemeAsync().Result;
            if (defaultAuthenticate != null)
            {
                var result = httpContext.AuthenticateAsync(defaultAuthenticate.Name).Result;
                if (result?.Principal != null)
                {
                }
            }
            */

            var isAuthenticated = context.User?.Identity?.IsAuthenticated;
            if (isAuthenticated.HasValue && isAuthenticated.Value)
            {
                if (requirement.ValidatePermission != null)
                {
                    //外部验证
                    var invockResult = requirement.ValidatePermission(context);
                    if (!invockResult)
                    {
                        context.Fail();
                    }
                }
                context.Succeed(requirement);
                // context?.Fail();
            }
            return Task.CompletedTask;

            /*
                //如果是AJAX请求 (包含了VUE等 的ajax)
                string requestType = filterContext.HttpContext.Request.Headers["X-Requested-With"];
                if (!string.IsNullOrEmpty(requestType) && requestType.Equals("XMLHttpRequest", StringComparison.CurrentCultureIgnoreCase))
                {
                    //ajax 的错误返回
                    //filterContext.Result = new StatusCodeResult(499); //自定义错误号 ajax请求错误 可以用来错没有权限判断 也可以不写 用默认的
                    context.Fail();
                }
                else
                {
                    //普通页面错误提示 就是跳转一个页面
                    //httpContext.Response.Redirect("/Home/visitDeny");//第一种方式跳转
                    filterContext.Result = new RedirectToActionResult("visitDeny", "Home", null);//第二种方式跳转
                    context.Fail();
                }
            */
        }
    }
}
